package com.itheima.web;

import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    @CachePut(value = "userCache",key="#user.id")//key的生成：userCache::1
    public User save(@RequestBody User user){
        userService.insert(user);
        return user;
    }

    @GetMapping
    @Cacheable(value = "userCache",key = "#id")
    public User getById(Long id){
        User user = userService.getById(id);
        return user;
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "userCache",key = "#id")//删除userCache下单个缓存数据
    public void deleteById(Long id){
        userService.deleteById(id);
    }


	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true)//删除userCache下所有缓存数据
    public void deleteAll(){
        userService.deleteAll();
    }

}
